package me.chyxion.spring.ext.exeptions;

import java.util.Set;
import java.util.HashSet;
import me.chyxion.spring.ext.DataModel;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * @version 0.0.1
 * @since 0.0.3
 * @author Shaun Chyxion <br />
 * chyxion@163.com <br />
 * Feb 3, 2015 1:44:09 PM
 */
public class BindingResultResolver implements ExceptionResolver {

	/* (non-Javadoc)
	 * @see me.chyxion.spring.ext.exeptions.ExceptionResolver#accept(java.lang.Throwable)
	 */
	@Override
	public boolean accept(Throwable ex) {
		return ex instanceof MethodArgumentNotValidException || 
				ex instanceof BindException;
	}

	/* (non-Javadoc)
	 * @see me.chyxion.spring.ext.exeptions.ExceptionResolver#process(me.chyxion.spring.ext.DataModel)
	 */
	@Override
	public DataModel process(DataModel model) {
		Throwable e = model.getException();
		BindingResult br = null;
		if (e instanceof MethodArgumentNotValidException) {
			br = ((MethodArgumentNotValidException) e).getBindingResult();
		}
		else if (e instanceof BindException) {
			br = ((BindException) e).getBindingResult();
		}
		if (br != null) {
			Set<String> message = new HashSet<String>();
			for (FieldError er : br.getFieldErrors()) {
				message.add(er.getField() + " " + er.getDefaultMessage());
			}
			model.setCode(InvalidParamException.CODE);
			model.setMessage(message);
		}
		return model;
	}
}
